package com.example.lottery.controller;

import cn.hutool.log.Log;
import com.example.lottery.common.errorcode.ControllerErrorCodeConstants;
import com.example.lottery.common.exception.ControllerException;
import com.example.lottery.common.pojo.CommonResult;
import com.example.lottery.common.utils.JacksonUtil;
import com.example.lottery.controller.param.CreateActivityParam;
import com.example.lottery.controller.param.PageParam;
import com.example.lottery.controller.result.CreateActivityResult;
import com.example.lottery.controller.result.FindActivityListResult;
import com.example.lottery.controller.result.GetActivityDetailResult;
import com.example.lottery.service.ActivityService;
import com.example.lottery.service.dto.ActivityDTO;
import com.example.lottery.service.dto.ActivityDetailDTO;
import com.example.lottery.service.dto.CreateActivityDTO;
import com.example.lottery.service.dto.PageListDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Comparator;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/activity")
public class ActivityController {
    @Autowired
    private ActivityService activityService;

    private static final Logger logger = LoggerFactory.getLogger(ActivityController.class);

    /**
     * 创建活动
     * @param param
     * @return
     */
    @RequestMapping("/create")
    public CommonResult<CreateActivityResult> createActivity(@Validated  @RequestBody CreateActivityParam param) {
        logger.info("createActivity，param：{}", JacksonUtil.writeValueAsString(param));
        return CommonResult.success(convertToCreateActivityResult(activityService.createActivity(param)));
    }

    /**
     * 创建活动返回结果的转换
     * @param activityDTO
     * @return
     */
    private CreateActivityResult convertToCreateActivityResult(CreateActivityDTO activityDTO) {
        if (activityDTO == null) {
            throw new ControllerException(ControllerErrorCodeConstants.CREATE_ACTIVITY_ERROR);
        }
        CreateActivityResult result = new CreateActivityResult();
        result.setActivityId(activityDTO.getActivityId());
        return result;
    }

    /**
     * 活动列表
     * @param param
     * @return
     */
    @RequestMapping("/find-list")
    public CommonResult<FindActivityListResult> findActivityList(PageParam param) {
        logger.info("findActivityList PageParam：{}",JacksonUtil.writeValueAsString(param));
        return CommonResult.success(convertToFindActivityListResult(activityService.findActivityList(param)));
    }

    /**
     * 活动列表返回结果的转换
     * @param activityList
     * @return
     */
    private FindActivityListResult convertToFindActivityListResult(PageListDTO<ActivityDTO> activityList) {
        if (null == activityList) {
            throw new ControllerException(ControllerErrorCodeConstants.FIND_ACTIVITY_LIST_ERROR);
        }

        FindActivityListResult result = new FindActivityListResult();
        result.setTotal(activityList.getTotal());
        result.setRecords(
                activityList.getRecords()
                        .stream()
                        .map(activityDTO -> {
                            FindActivityListResult.ActivityInfo activityInfo = new FindActivityListResult.ActivityInfo();
                            activityInfo.setActivityId(activityDTO.getActivityId());
                            activityInfo.setActivityName(activityDTO.getActivityName());
                            activityInfo.setDescription(activityDTO.getDescription());
                            activityInfo.setValid(activityDTO.valid());
                            return activityInfo;
                        }).collect(Collectors.toList())
        );
        return result;
    }

    /**
     * 活动详情
     * @param activityId
     * @return
     */
    @RequestMapping("/detail")
    public CommonResult<GetActivityDetailResult> getActivityDetail(Long activityId) {
        logger.info("getActivityDetail,activityId:{}", activityId);
        ActivityDetailDTO detailDTO = activityService.getActivityDetail(activityId);
        return CommonResult.success(convertToGerActivityDetailResult(detailDTO));
    }

    /**
     * 活动详情的返回结果转换
     * @param detailDTO
     * @return
     */
    private GetActivityDetailResult convertToGerActivityDetailResult(ActivityDetailDTO detailDTO) {
        if (null == detailDTO) {
            throw new ControllerException(ControllerErrorCodeConstants.GET_ACTIVITY_DETAIL_ERROR);
        }

        //活动自身的基本信息
        GetActivityDetailResult result = new GetActivityDetailResult();
        result.setActivityId(detailDTO.getActivityId());
        result.setActivityName(detailDTO.getActivityName());
        result.setDescription(detailDTO.getDesc());
        result.setValid(detailDTO.valid());

        //抽奖顺序，一、二、三等奖(这个活动关联的奖品详情信息表)
        result.setPrizes(detailDTO.getPrizeListDTO()
                .stream()
                .sorted(Comparator.comparingInt(prizeDTO->prizeDTO.getTiers().getCode()))//默认升序排序
                .map(prizeDTO -> {
                    GetActivityDetailResult.Prize prize = new GetActivityDetailResult.Prize();
                    prize.setPrizeId(prizeDTO.getPrizeId());
                    prize.setName(prizeDTO.getName());
                    prize.setImageUrl(prizeDTO.getImageUrl());
                    prize.setPrice(prizeDTO.getPrice());
                    prize.setDescription(prizeDTO.getDescription());
                    prize.setPrizeTierName(prizeDTO.getTiers().getMessage());
                    prize.setPrizeAmount(prizeDTO.getPrizeAmount());
                    prize.setValid(prizeDTO.valid());
                    return prize;
                }).collect(Collectors.toList()));

        //参与这个活动的用户详情信息
        result.setUsers(detailDTO.getUserListDTO().stream().map(userDTO -> {
            GetActivityDetailResult.User user = new GetActivityDetailResult.User();
            user.setUserId(userDTO.getUserId());
            user.setUserName(userDTO.getUserName());
            user.setValid(userDTO.valid());
            return user;
        }).collect(Collectors.toList()));


        return result;
    }
}
